// 包声明 package main 表示一个可独立执行的程序
package main

// 引入包
import (
	"fmt"
	"log"
	"net/http"

	socketio "github.com/googollee/go-socket.io"
)

// 入口函数
func main() {
	fmt.Println("启动SocketServer!")

	server := socketio.NewServer(nil)
	if server == nil {
		log.Fatal("server is null")
	}
	server.OnConnect("/", func(s socketio.Conn) error {
		fmt.Println("/: OnConnect", s.ID(), server.Count())
		s.Emit("hello", "world")
		return nil
	})
	server.OnEvent("/", "heartbeat", func(s socketio.Conn, msg string) {
		fmt.Println("/heartbeat: msg receive", msg)
	})
	server.OnEvent("/", "echo", func(s socketio.Conn, msg string) {
		fmt.Println("/echo: msg received", msg)
		s.Emit("echo", "server echo string: "+msg)
	})
	// server.OnEvent("/", "echo", func(s socketio.Conn, msg int) {
	// 	fmt.Println("/echo: msg received", msg)
	// 	s.Emit("echo", "server echo int: ", msg)
	// })
	server.OnError("/", func(s socketio.Conn, e error) {
		fmt.Println("/:error", e)
	})
	server.OnDisconnect("/", func(s socketio.Conn, reason string) {
		fmt.Println("/:closed", s.ID(), reason)
	})

	go server.Serve()
	defer server.Close()

	http.Handle("/socket.io/", server)
	http.Handle("/", http.FileServer(http.Dir("../asset")))

	log.Println("Serving at localhost:8000...")
	log.Fatal(http.ListenAndServe(":8000", nil))
}
